"""
数据库管理API接口
提供数据库状态查看、初始化等功能
"""

from datetime import datetime
from typing import List, Dict, Any
from fastapi import APIRouter, Depends, Query
from tortoise.queryset import QuerySet

from app.core.auth import get_current_superuser, get_current_user_required
from app.schemas.base.login import JWTPayload
from app.utils.request import RequestHandler
from app.core.database import db_manager, get_database_status
from app.models.base.system import DatabaseInitLog, SystemConfig, OperationLog
from app.models.base.user import User, UserLoginLog

router = APIRouter(prefix="/database", tags=["数据库管理"])


@router.get("/status", summary="获取数据库状态")
async def get_db_status(
    current_user: JWTPayload = Depends(get_current_superuser)
):
    """
    获取数据库状态信息
    需要超级用户权限
    """
    try:
        status_info = await get_database_status()
        
        return RequestHandler.success(
            data=status_info,
            message="数据库状态获取成功",
            remarks=f"管理员 {current_user.username} 查看数据库状态"
        )
        
    except Exception as e:
        return RequestHandler.server_error(
            message="获取数据库状态失败",
            remarks=f"错误详情: {str(e)}"
        )


@router.post("/init", summary="重新初始化数据库")
async def reinit_database(
    current_user: JWTPayload = Depends(get_current_superuser),
    create_tables: bool = Query(True, description="是否创建数据表"),
    init_data: bool = Query(True, description="是否初始化默认数据")
):
    """
    重新初始化数据库
    需要超级用户权限，谨慎操作
    """
    try:
        # 重新初始化数据库
        success = await db_manager.initialize_database(create_tables=create_tables)
        
        if not success:
            return RequestHandler.server_error(
                message="数据库初始化失败",
                remarks="请检查数据库配置和连接"
            )
        
        # 初始化默认数据
        if init_data:
            await db_manager.init_default_data()
        
        return RequestHandler.success(
            data={
                "initialization_time": datetime.now().isoformat(),
                "create_tables": create_tables,
                "init_data": init_data,
                "operator": current_user.username
            },
            message="数据库重新初始化成功",
            remarks="数据库已重新初始化，所有表结构已更新"
        )
        
    except Exception as e:
        return RequestHandler.server_error(
            message="数据库初始化失败",
            remarks=f"错误详情: {str(e)}"
        )


@router.get("/init-logs", summary="获取数据库初始化日志")
async def get_init_logs(
    current_user: JWTPayload = Depends(get_current_superuser),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量")
):
    """
    获取数据库初始化日志
    需要超级用户权限
    """
    try:
        # 计算偏移量
        offset = (page - 1) * page_size
        
        # 查询日志
        logs = await DatabaseInitLog.filter(is_deleted=False).order_by('-created_at').offset(offset).limit(page_size)
        total = await DatabaseInitLog.filter(is_deleted=False).count()
        
        # 转换为字典格式
        log_data = []
        for log in logs:
            log_data.append({
                "id": log.id,
                "version": log.version,
                "init_type": log.init_type,
                "status": log.status,
                "message": log.message,
                "execution_time": log.execution_time,
                "created_at": log.created_at.isoformat()
            })
        
        return RequestHandler.success(
            data={
                "logs": log_data,
                "pagination": {
                    "page": page,
                    "page_size": page_size,
                    "total": total,
                    "total_pages": (total + page_size - 1) // page_size
                }
            },
            message="初始化日志获取成功",
            remarks=f"共 {total} 条初始化记录"
        )
        
    except Exception as e:
        return RequestHandler.server_error(
            message="获取初始化日志失败",
            remarks=f"错误详情: {str(e)}"
        )


@router.get("/tables", summary="获取数据表信息")
async def get_tables_info(
    current_user: JWTPayload = Depends(get_current_superuser)
):
    """
    获取数据库表信息
    需要超级用户权限
    """
    try:
        # 获取所有模型的统计信息
        tables_info = []
        
        # 用户相关表
        user_count = await User.filter(is_deleted=False).count()
        login_log_count = await UserLoginLog.filter(is_deleted=False).count()
        
        tables_info.extend([
            {
                "table_name": "users",
                "model_name": "User",
                "description": "用户表",
                "record_count": user_count
            },
            {
                "table_name": "user_login_logs", 
                "model_name": "UserLoginLog",
                "description": "用户登录日志表",
                "record_count": login_log_count
            }
        ])
        
        # 系统相关表
        config_count = await SystemConfig.filter(is_deleted=False).count()
        operation_log_count = await OperationLog.filter(is_deleted=False).count()
        init_log_count = await DatabaseInitLog.filter(is_deleted=False).count()
        
        tables_info.extend([
            {
                "table_name": "system_configs",
                "model_name": "SystemConfig", 
                "description": "系统配置表",
                "record_count": config_count
            },
            {
                "table_name": "operation_logs",
                "model_name": "OperationLog",
                "description": "操作日志表", 
                "record_count": operation_log_count
            },
            {
                "table_name": "database_init_logs",
                "model_name": "DatabaseInitLog",
                "description": "数据库初始化日志表",
                "record_count": init_log_count
            }
        ])
        
        return RequestHandler.success(
            data={
                "tables": tables_info,
                "total_tables": len(tables_info),
                "query_time": datetime.now().isoformat()
            },
            message="数据表信息获取成功",
            remarks="显示所有模型对应的数据表统计信息"
        )
        
    except Exception as e:
        return RequestHandler.server_error(
            message="获取数据表信息失败", 
            remarks=f"错误详情: {str(e)}"
        )


@router.get("/configs", summary="获取系统配置")
async def get_system_configs(
    current_user: JWTPayload = Depends(get_current_user_required),
    public_only: bool = Query(False, description="是否只显示公开配置")
):
    """
    获取系统配置
    普通用户只能查看公开配置，超级用户可以查看所有配置
    """
    try:
        # 根据用户权限决定查询条件
        if current_user.is_superuser and not public_only:
            configs = await SystemConfig.filter(is_deleted=False).order_by('key')
        else:
            configs = await SystemConfig.filter(is_deleted=False, is_public=True).order_by('key')
        
        # 转换为字典格式
        config_data = []
        for config in configs:
            config_info = {
                "key": config.key,
                "value": config.value,
                "description": config.description,
                "config_type": config.config_type,
                "is_public": config.is_public,
                "updated_at": config.updated_at.isoformat()
            }
            
            # 非超级用户不显示敏感信息
            if not current_user.is_superuser and not config.is_public:
                config_info["value"] = "***"
                
            config_data.append(config_info)
        
        return RequestHandler.success(
            data={
                "configs": config_data,
                "total": len(config_data),
                "user_type": "superuser" if current_user.is_superuser else "normal_user",
                "public_only": public_only or not current_user.is_superuser
            },
            message="系统配置获取成功",
            remarks=f"用户 {current_user.username} 查看系统配置"
        )
        
    except Exception as e:
        return RequestHandler.server_error(
            message="获取系统配置失败",
            remarks=f"错误详情: {str(e)}"
        )


@router.put("/configs/{config_key}", summary="更新系统配置")
async def update_system_config(
    config_key: str,
    value: str,
    current_user: JWTPayload = Depends(get_current_superuser),
    description: str = Query(None, description="配置描述"),
    config_type: str = Query("string", description="配置类型")
):
    """
    更新系统配置
    需要超级用户权限
    """
    try:
        # 更新配置
        config = await SystemConfig.set_config(
            key=config_key,
            value=value,
            description=description,
            config_type=config_type
        )
        
        return RequestHandler.success(
            data={
                "key": config.key,
                "value": config.value,
                "description": config.description,
                "config_type": config.config_type,
                "updated_by": current_user.username,
                "updated_at": config.updated_at.isoformat()
            },
            message="系统配置更新成功",
            remarks=f"配置 {config_key} 已由管理员 {current_user.username} 更新"
        )
        
    except Exception as e:
        return RequestHandler.server_error(
            message="更新系统配置失败",
            remarks=f"错误详情: {str(e)}"
        )


@router.get("/statistics", summary="获取数据库统计信息")
async def get_database_statistics(
    current_user: JWTPayload = Depends(get_current_superuser)
):
    """
    获取数据库统计信息
    需要超级用户权限
    """
    try:
        # 统计各表数据量
        stats = {
            "users": {
                "total": await User.all().count(),
                "active": await User.filter(is_active=True, is_deleted=False).count(),
                "superusers": await User.filter(is_superuser=True, is_deleted=False).count(),
                "today_registered": await User.filter(
                    created_at__gte=datetime.now().replace(hour=0, minute=0, second=0, microsecond=0),
                    is_deleted=False
                ).count()
            },
            "login_logs": {
                "total": await UserLoginLog.all().count(),
                "today": await UserLoginLog.filter(
                    login_time__gte=datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
                ).count(),
                "successful": await UserLoginLog.filter(login_success=True).count(),
                "failed": await UserLoginLog.filter(login_success=False).count()
            },
            "system": {
                "configs": await SystemConfig.filter(is_deleted=False).count(),
                "operation_logs": await OperationLog.filter(is_deleted=False).count(),
                "init_logs": await DatabaseInitLog.filter(is_deleted=False).count()
            }
        }
        
        return RequestHandler.success(
            data={
                "statistics": stats,
                "generated_at": datetime.now().isoformat(),
                "generated_by": current_user.username
            },
            message="数据库统计信息获取成功",
            remarks="实时统计数据"
        )
        
    except Exception as e:
        return RequestHandler.server_error(
            message="获取统计信息失败",
            remarks=f"错误详情: {str(e)}"
        )